<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="科目" prop="subject">
        <el-input v-model="queryParams.subject" placeholder="请输入科目" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="课程名" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入课程名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="课程描述" prop="describe">
        <el-input v-model="queryParams.describe" placeholder="请输入课程描述" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="讲师姓名" prop="teacherName">
        <el-select v-model="queryParams.teacherName" placeholder="选择" clearable :style="{ width: '100%' }">
          <el-option v-for="(item, index) in teacherList" :key="index" :label="item.nickName" :value="item.nickName"
            :disabled="item.disabled" @keyup.enter.native="handleQuery"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['course:course:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['course:course:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['course:course:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['course:course:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程id" align="center" prop="id" />
      <el-table-column label="类型：科目" align="center" prop="subject" />
      <el-table-column label="课程图片">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover">
            <img :src="scope.row.coverImage" alt="" style="width: 150px;height: 150px">
            <img slot="reference" :src="scope.row.coverImage" style="width: 50px;height: 50px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="课程名" align="center" prop="title" />
      <el-table-column label="课程描述" align="center" prop="describe" />
      <el-table-column label="主讲老师" align="center" prop="teacherId" />
      <el-table-column label="讲师姓名" align="center" prop="teacherName" />
      <el-table-column label="发布课程的用户id" align="center" prop="createdBy" />
      <el-table-column label="删除标志" align="center" prop="deleteFlag" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['course:course:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['course:course:remove']">删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['course:chapter:edit', 'course:course:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleChapter" icon="el-icon-key">章节详情
              </el-dropdown-item>
              <el-dropdown-item command="handleUserChosen" icon="el-icon-circle-check">查看选课学生
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科目" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入科目" />
        </el-form-item>
        <el-form-item label="封面" prop="coverImage">
          <el-upload ref="upload" style="display: inline" drag action="" :http-request="handleUpload"
            :auto-upload="false" multiple :limit="1" list-type="picture">
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        </el-form-item>
        <el-form-item label="课程名" prop="title">
          <el-input v-model="form.title" placeholder="请输入课程名" />
        </el-form-item>
        <el-form-item label="课程描述" prop="describe">
          <el-input v-model="form.describe" placeholder="请输入课程描述" />
        </el-form-item>
        <el-form-item label="主讲老师" prop="teacherId">
          <el-select v-model="form.teacherId" @change="OnTeacherSelected" placeholder="请输入主讲老师">
            <el-option v-for="teacher in teacherList" :key="teacher.userId" :value="teacher.userId"
              :label="teacher.nickName" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCourse, listTeacher, getCourse, delCourse, addCourse, updateCourse } from "@/api/course/course";
import { getFileMD5, getBaseUrl, addFile } from "@/api/file/file";

export default {
  name: "Course",
  data() {
    return {
      upload: null,
      fileList: [],
      baseUrl: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 老师List
      teacherList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subject: null,
        title: null,
        describe: null,
        teacherId: null,
        teacherName: null,
        createdBy: null,
        deleteFlag: null
      },
      // 表单参数
      form: {
        coverImage: "",
      },
      // 表单校验
      rules: {
        subject: [
          { required: true, message: "类型：科目不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "课程名不能为空", trigger: "blur" }
        ],
        describe: [
          { required: true, message: "课程描述不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "主讲老师不能为空", trigger: "blur" }
        ],
        deleteFlag: [
          { required: true, message: "删除标志不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleUpload(param) {
      let file = param.file;
      console.log(file)
      getFileMD5(file).then(res => {
        let fileMd5 = res.msg
        console.log(fileMd5)
        addFile(file, fileMd5).then(response => {
          console.log(response)
          this.form.coverImage = this.baseUrl + response.url
          this.$modal.msgSuccess("新增成功");
          this.upload = null;
          this.fileList = [];
        });
      })
    },
    OnTeacherSelected(val) {
      if (val) {
        let obj = {}
        obj = this.teacherList.find((item) => {
          return item.userId == val;
        })
        console.log(obj)
        this.form.teacherName = obj.nickName
      }
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      getBaseUrl().then(res => {
        this.baseUrl = res.msg;
      })
      listTeacher().then(res => {
        this.teacherList = res.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        subject: null,
        title: null,
        describe: null,
        teacherId: null,
        teacherName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCourse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCourse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除课程编号为"' + ids + '"的数据项？').then(function () {
        return delCourse(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/course/export', {
        ...this.queryParams
      }, `course_${new Date().getTime()}.xlsx`)
    },
    // 查看章节信息
    handleChapter: function (row) {
      const courseId = row.id;
      console.log(courseId)
      this.$router.push("/course/course-chapter/chapter/" + courseId);
    },
    // 查看用户选课
    handleUserChosen: function (row) {
      const courseId = row.id;
      console.log(courseId)
      this.$router.push("/course/course-user/course/" + courseId);
    },
    // 命令
    handleCommand(command, row) {
      switch (command) {
        case "handleChapter":
          this.handleChapter(row);
          break;
        case "handleUserChosen":
          this.handleUserChosen(row);
          break;
        default:
          break;
      }
    }
  }
};
</script>
